package kite.sso.filter;

import kite.sso.message.UserEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;

/**
 * 功能描述: 系统可访问过滤<br>
 * 所属包名: kite.sso.aspect<br>
 * 创建人　: 白剑<br>
 * 创建时间: 06/12/2018 22:54 Tuesday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@WebFilter(asyncSupported = true, urlPatterns = {"/oauth/authorize"})
public class SsoAccessFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 功能描述: 如果登录用户没有系统访问权限，则直接跳过认证阶段，返回无权限访问系统信息<br>
     * 创建人　: 白剑<br>
     * 创建时间: 2018/06/12 23:11:29<br>
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserEntity userEntity = (UserEntity) authentication.getPrincipal();

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String sysAddress = Arrays.toString(httpServletRequest.getParameterMap().get("redirect_uri"));
        sysAddress = sysAddress.replace("[http://", "");
        sysAddress = sysAddress.substring(0, sysAddress.indexOf("/"));

        // TODO 怎么判断用户是否有系统访问权限，暂定根据IP:PORT来判断
        if (!userEntity.getUserAccessSys().contains(sysAddress)) {
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
